/**
 * Software License, Version 1.0 Copyright 2003 The Trustees of Indiana
 * University. All rights reserved. Redistribution and use in source and binary
 * forms, with or without modification, are permitted provided that the
 * following conditions are met: 1) All redistributions of source code must
 * retain the above copyright notice, the list of authors in the original source
 * code, this list of conditions and the disclaimer listed in this license; 2)
 * All redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the disclaimer listed in this license in the
 * documentation and/or other materials provided with the distribution; 3) Any
 * documentation included with all redistributions must include the following
 * acknowledgement: "This product includes software developed by the Community
 * Grids Lab. For further information contact the Community Grids Lab at
 * http://communitygrids.iu.edu/." Alternatively, this acknowledgement may
 * appear in the software itself, and wherever such third-party acknowledgments
 * normally appear. 4) The name Indiana University or Community Grids Lab or
 * NaradaBrokering, shall not be used to endorse or promote products derived
 * from this software without prior written permission from Indiana University.
 * For written permission, please contact the Advanced Research and Technology
 * Institute ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202. 5)
 * Products derived from this software may not be called NaradaBrokering, nor
 * may Indiana University or Community Grids Lab or NaradaBrokering appear in
 * their name, without prior written permission of ARTI. Indiana University
 * provides no reassurances that the source code provided does not infringe the
 * patent or any other intellectual property rights of any other entity. Indiana
 * University disclaims any liability to any recipient for claims brought by any
 * other entity based on infringement of intellectual property rights or
 * otherwise. LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH
 * NO WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY
 * GIVES NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF
 * INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS.
 * INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS",
 * "VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.
 * LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR
 * ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION
 * GENERATED USING SOFTWARE.
 */
/**
 * 
 */
package cgl.narada.test.transport.multipleHTTPClients;

import java.util.Properties;

import org.apache.log4j.Logger;

import cgl.narada.event.NBEvent;
import cgl.narada.event.TemplateProfileAndSynopsisTypes;
import cgl.narada.matching.Profile;
import cgl.narada.service.ServiceException;
import cgl.narada.service.client.ClientService;
import cgl.narada.service.client.EventConsumer;
import cgl.narada.service.client.EventProducer;
import cgl.narada.service.client.NBEventListener;
import cgl.narada.service.client.SessionService;
import cgl.narada.util.SystemInit;
import cgl.narada.util.SystemNotInitializedException;

/**
 * <br>
 * 
 * @author Harshawardhan Gadgil (hgadgil@grids.ucs.indiana.edu)<br>
 *         Created: Mar 13, 2006<br>
 */
public class HTTPConnReceiver implements NBEventListener {
	static Logger log = Logger.getLogger("SOAPNBTransport");

	private String topic;

	private Profile profile;
	private EventProducer producer;
	private EventConsumer consumer;

	private ClientService clientService;

	private int entityId;

	public HTTPConnReceiver(String _topic, int id) {
		topic = _topic;
		entityId = id;
	}

	public String sslCertPort;

	public static void main(String[] args) {

		SystemInit.init();

		if (args.length < 5) {
			System.out.println("USAGE:");
			System.out
					.println("java cgl.narada.test.transport.multipleHTTPClients.HTTPConnReceiver <params>");
			System.out
					.println("params: topicName entityid brokerHost port protocol [sslCertPort]");
		}

		HTTPConnReceiver receiver = new HTTPConnReceiver(args[0], Integer
				.parseInt(args[1]));

		if (args.length == 6) receiver.sslCertPort = args[5];
		receiver.initTransport(args[2], args[3], args[4], "test", "test");
	}

	/**
	 * Connects to the specified Broker and subscribes to the stream on
	 * specified topic
	 * 
	 * @param param -
	 *            The topic to subscribe to
	 */

	public void initTransport(String host, String port, String protocol,
			String username, String password) {

		System.out.println("Topic: >>" + topic + "<<");
		System.out.println("\n******* USING ENTITYID: " + entityId + "\n");

		try {
			clientService = SessionService.getClientService(entityId);
		}
		catch (ServiceException e) {
			log.error("Unable to load Client Service");

		}

		// These properties pertain to setting up a TCP link
		Properties props = new Properties();

		props.put("hostname", host);
		props.put("portnum", port);
		props.put("username", username);
		props.put("password", password);
		boolean connected = false;

		String connString = protocol + "@" + props.getProperty("hostname")
				+ ":" + props.getProperty("portnum");

		if (protocol.equals("ssl")) {
			if (sslCertPort == null) {
				try {
					props
							.put(
									"acceptor.trustStore",
									SystemInit
											.getInitData(SystemInit.SYS_BROKER_CERTIFICATE_TRUSTRORE));
					props
							.put(
									"acceptor.trustStorePassword",
									SystemInit
											.getInitData(SystemInit.SYS_BROKER_TRUSTSTORE_PASSWORD));
				}
				catch (SystemNotInitializedException e) {
					e.printStackTrace();
				}
			}
			else {
				props.put("controlserver.port", sslCertPort);
				connString += " SSLCertPort: " + sslCertPort;
			}
		}

		log.info("Connecting to: " + connString);

		try {
			clientService.initializeBrokerCommunications(props, protocol);
			connected = true;
		}
		catch (ServiceException e1) {
			log.error("Unable to connect : " + connString);
		}

		if (!connected) {
			log.fatal("Could not connect ! Exiting ");
			System.exit(0);
		}

		try {
			profile = clientService.createProfile(
					TemplateProfileAndSynopsisTypes.STRING, topic);

			consumer = clientService.createEventConsumer(this);
			consumer.subscribeTo(profile);

			producer = clientService.createEventProducer();
		}
		catch (Exception e) {
			log.error("Unable to create subscribe profile ", e);
		}
	}

	public synchronized void onEvent(NBEvent nbEvent) {

		try {
			byte[] content = nbEvent.getContentPayload();
			log.info("Rcvd:\t" + new String(content));

			String msg = new String(content, 0, content.length);
		}
		catch (Exception e) {
			log.error("Error reading bytes. ", e);
		}

	}

	public void closeTransport() {
		try {
			clientService.closeBrokerConnection();
			clientService.terminateServices();
		}
		catch (ServiceException e) {}
	}

	// public void sendMessage(byte[] message) throws Exception {
	//
	// NBEvent nbEvent = producer.generateEvent(
	// TemplateProfileAndSynopsisTypes.STRING, topic, message);
	//
	// producer.publishEvent(nbEvent);
	// log.debug("Event published");
	// }

}
